<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="离职员工" prop="recordUserId">
        <UserSelect @node-change="handleNodeChange" v-model="formData.recordUserId" />
      </el-form-item>
      <el-form-item label="所在部门" prop="recordDeptName">
        <el-input v-model="formData.recordDeptName" placeholder="请输入所在部门" disabled />
      </el-form-item>
      <el-form-item label="部门负责人" prop="leaderUserName">
        <el-input v-model="formData.leaderUserName" placeholder="请输入部门负责人" disabled />
      </el-form-item>
      <el-form-item label="离职日期" prop="resignationDate">
        <el-date-picker
          v-model="formData.resignationDate"
          type="date"
          value-format="x"
          placeholder="选择离职日期"
        />
      </el-form-item>
      
      
      <el-form-item label="接收人" prop="recipientId">
        <UserSelect @node-change="handleRecipientNodeChange" v-model="formData.recipientId" />
      </el-form-item>
      <el-form-item label="资料交接状态" prop="handoverStatus">
        <el-select v-model="formData.handoverStatus" placeholder="请选择资料交接状态">
          <el-option
            v-for="dict in getIntDictOptions(DICT_TYPE.OA_HANDOVER_STATUS)"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="参与交接人员" prop="handoverIdsList">
        <UserSelectMultiple @node-change="handleMultipleNodeChange" v-model="formData.handoverIdsList" />
      </el-form-item>
      <el-form-item label="离职原因" prop="resignationReason">
        <el-input v-model="formData.resignationReason" placeholder="请输入离职原因" type="textarea" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getIntDictOptions, DICT_TYPE } from '@/utils/dict'
import { ResignationRecordsApi, ResignationRecordsVO } from '@/api/oa/resignationrecords'
import UserSelect  from '@/views/system/user/UserSelect.vue'
import UserSelectMultiple  from '@/views/system/user/UserSelectMultiple.vue'
import * as DeptApi from '@/api/system/dept'
import * as UserApi from '@/api/system/user'

/** 离职档案 表单 */
defineOptions({ name: 'ResignationRecordsForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  recordUserId: undefined,
  recordRealName: undefined,
  resignationDate: undefined,
  recordDeptId: undefined,
  recordDeptName: undefined,
  leaderUserId: undefined,
  leaderUserName: undefined,
  recipientId: undefined,
  recipientName: undefined,
  handoverStatus: undefined,
  handoverIds: undefined,
  handoverIdsList: undefined,
  handoverNames: '',
  resignationReason: undefined,
})
const formRules = reactive({
  recordUserId: [{ required: true, message: '离职员工id不能为空', trigger: 'blur' }],
  recordRealName: [{ required: true, message: '离职员工姓名不能为空', trigger: 'blur' }],
  resignationDate: [{ required: true, message: '离职日期不能为空', trigger: 'blur' }],
  recordDeptId: [{ required: true, message: '离职员工所在部门不能为空', trigger: 'blur' }],
  recordDeptName: [{ required: true, message: '离职员工所在部门不能为空', trigger: 'blur' }],
  leaderUserId: [{ required: true, message: '部门负责人不能为空', trigger: 'blur' }],
  leaderUserName: [{ required: true, message: '部门负责人不能为空', trigger: 'blur' }],
  recipientId: [{ required: true, message: '接收人不能为空', trigger: 'blur' }],
  recipientName: [{ required: true, message: '接收人不能为空', trigger: 'blur' }],
  handoverStatus: [{ required: true, message: '资料交接状态不能为空', trigger: 'change' }],
})
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ResignationRecordsApi.getResignationRecords(id)
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as ResignationRecordsVO
    if (formType.value === 'create') {
      await ResignationRecordsApi.createResignationRecords(data)
      // 关闭员工登录账号
      await UserApi.updateUserStatus(data.recordUserId,1)
      message.success(t('common.createSuccess'))
    } else {
      await ResignationRecordsApi.updateResignationRecords(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    recordUserId: undefined,
    recordRealName: undefined,
    resignationDate: undefined,
    recordDeptId: undefined,
    recordDeptName: undefined,
    leaderUserId: undefined,
    leaderUserName: undefined,
    recipientId: undefined,
    recipientName: undefined,
    handoverStatus: undefined,
    handoverIds: undefined,
    handoverIdsList: undefined,
    handoverNames: '',
    resignationReason: undefined,
  }
  formRef.value?.resetFields()
}

/** 离职员工被点击 */
const handleNodeChange = async (row) => {
  formData.value.recordUserId = row.id
  formData.value.recordRealName = row.nickname

  // 补充部门信息
  const deptInfo = await DeptApi.getDept(row.deptId)
  formData.value.recordDeptId = deptInfo.id
  formData.value.recordDeptName = deptInfo.name
  formData.value.leaderUserId = deptInfo.leaderUserId

  if(deptInfo.leaderUserId){
    const leaderInfo = await UserApi.getUser(deptInfo.leaderUserId)
    formData.value.leaderUserName = leaderInfo.nickname
  }else{
    formData.value.leaderUserName = undefined
  }
  
}

/** 接收人被点击事件 */
const handleRecipientNodeChange = async (row) =>{
  formData.value.recipientId = row.id
  formData.value.recipientName = row.nickname
}

/** 参与交接人员被点击事件 */
const handleMultipleNodeChange = async (array) => {
  // 初始化names变量
  let names = ''
  
  // 安全获取并处理handoverIds
  const idString = String(formData.value.handoverIdsList || '')
  const targetIds = idString.split(',').filter(id => id.trim() !== '')
  
  // 处理每个ID
  targetIds.forEach(id => {
    const matchedItem = array.find(item => String(item.id || '') === id)
    if (matchedItem && matchedItem.nickname) {
      names += matchedItem.nickname+','
    }
  })

  
  // 去除末尾逗号并赋值
  const cleanString = names.replace(/,$/, '')
  formData.value.handoverNames = cleanString
}
</script>